package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.LoginFormDTO;
import com.demo.dto.Result;
import com.demo.dto.UserDTO;
import com.demo.entity.User;
import com.demo.mapper.UserMapper;
import com.demo.service.IUserService;
import com.demo.utils.RegexUtils;
import com.demo.utils.SystemConstants;
import com.demo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.demo.utils.RedisConstants.*;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)){
            //2.不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }
        //3.符合，生成验证码 长度为6
        String code = RandomUtil.randomNumbers(6);

        //4.保存验证码到Redis中 key为用户手机
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY +phone,code);
//        session.setAttribute("code",code);
        //设置code在redis中的过期时间
        stringRedisTemplate.expire(LOGIN_CODE_KEY +phone,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码
        //这里不调用第三方，将验证码保存在日志中
        log.debug("发送短信验证码成功，验证码：{}", code);
        //6.返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号不合法");
        }
        //2.校验验证码
        //从redis中取出code
        String redisCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        //redis中的code与用户输入的code作比较
        if (redisCode == null || !redisCode.equals(loginForm.getCode())){
            //3.错误返回
            return Result.fail("验证码错误");
        }
        //4.一致，根据手机号查用户
        //mybatis-plus 根据字段phone查user表信息
        User user = query().eq("phone", phone).one();
        //5.判断用户是否存在
        if (user == null){
            //6.不存在创建用户保存
            user = createUser(phone,loginForm.getPassword());
        }

        //TODO 7.将用户信息存在redis中
        //TODO 7.1 生成一个token
        String token = UUID.randomUUID().toString(true);
        //TODO 7.2 将user对象作为hashMap进行存储
        //不返回user全部信息，只返回UserDTO中的部分信息，BeanUtil方法进行替换
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        //TODO 7.3存储
        stringRedisTemplate.opsForHash().putAll(LOGIN_TOKEN_KEY + token,userMap);
        //TODO 7.4设置token30min过期
        stringRedisTemplate.expire(LOGIN_TOKEN_KEY + token,LOGIN_TOKEN_TTL,TimeUnit.MINUTES);
        //TODO 8.返回这个token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        //3，拼接key
        String keySuffix = userId + now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        String key = USER_SIGN_KEY + keySuffix;
        //4.获取当天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.写入Redis BitMap
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        //3，拼接key
        String keySuffix = userId + now.format(DateTimeFormatter.ofPattern(":yyyy/MM"));
        String key = USER_SIGN_KEY + keySuffix;
        //4.获取当天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.获取本月截止到今天为止的签到记录，返回的是一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue()
                .bitField(key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result == null || result.isEmpty()){
            //没有签到过
            return Result.ok("");
        }
        Long num = result.get(0);
        //没有签到过
        if (num == null || num == 0){
            return Result.ok("");
        }
        //6.循环遍历
        int count = 0;
        while (true){
            //6.1与1做与运算，得到最后一次记录的bit位
            //6.2判断bit位的数值 为0未签到
            if ((num & 1) == 0){
                break;
            }else {
                //6.3不为0说明签到，次数加1
                count++;
            }
            //6.4数字右移一位，放弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }

    //创建新用户
    private User createUser(String phone,String password) {
        //1.创建用户信息
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        String name = SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(5);
        user.setNickName(name);
        //2.保存用户
        save(user);
        return user;
    }
}
